package com.interesting;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;

import com.interesting.base.core.BaseActivity;
import com.interesting.base.http.HttpUtil;
import com.interesting.base.utils.Constant;
import com.interesting.client.application.AppHolder;

public class StartActivity extends BaseActivity {
	private String username;
	private String password;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getSupportActionBar().hide();
		setContentView(R.layout.start_activity);
		if (savedInstanceState == null) {

			SharedPreferences sp = getSharedPreferences(Constant.SHARE_PREFERENCE, Activity.MODE_PRIVATE);
			username = sp.getString(Constant.USERNAME, "");
			password = sp.getString(Constant.PASSWORD, "");
			new UserInfoAsyncTask().execute(username, password);
		}
	}

	/** 用户信息 自动登录 */

	class UserInfoAsyncTask extends AsyncTask<String, Void, String> {

		@Override
		protected String doInBackground(String... params) {
			Map<String, String> request = new HashMap<String, String>();
			request.put("act", "login");
			request.put("username", params[0]);
			request.put("password", params[1]);
			request.put("imei", AppHolder.getInsatnce().getImei(getApplicationContext()));
			request.put("phone", AppHolder.getInsatnce().getPhone(getApplicationContext()));
			request.put("imsi", AppHolder.getInsatnce().getImsi(getApplicationContext()));
			request.put("version", AppHolder.getInsatnce().getVersion(getApplicationContext()));
			return HttpUtil.post(request);
		}

		@Override
		protected void onPostExecute(String result) {
			JSONObject response = HttpUtil.parseResult(result);
			if (response != null) {
				try {
					JSONObject userData = response.getJSONObject("userData");
					AppHolder.getInsatnce().user.setUserId(userData.getString("userId"));
					AppHolder.getInsatnce().user.setUserName(userData.getString("username"));
					AppHolder.getInsatnce().user.setUserIcon(userData.getString("icon"));
				} catch (JSONException e) {
					e.printStackTrace();
				}finally{
					Intent intent = new Intent(StartActivity.this, MainActivity.class);
					startActivity(intent);
					finish();
				}
			} else {
				Intent intent = new Intent(StartActivity.this, MainActivity.class);
				startActivity(intent);
				finish();
			}
		}
	}
}
